package com.imay.live.activity.dynamics;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.base.helper.NetworkHelper;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.adapter.CommentAdapter;
import com.imay.live.heartlikeslib.swipelayout.SwipeHorizontalMenuLayout;
import com.imay.live.heartlikeslib.swipelayout.SwipeMenuRecyclerView;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.DymaicsUpdateHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.manager.EditTextManager;
import com.imay.live.manager.SensitiveWordFilterManager;
import com.imay.live.model.CommentModel;
import com.imay.live.model.CommentTotalModel;
import com.imay.live.model.FeedModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.base.util.SpannableStringUtils;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.LoadView;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.R;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.List;

import static com.imay.live.proto.helper.ProtoRequestHelper.task;


/**
 * 评论
 * Created by chan on 2017/3/29.
 */
public class CommentActivity extends BaseRequestActivity implements OnTouchListener, View.OnClickListener, KeyboardChangeListener.KeyBoardListener {

    private Context mContext;

    private int status;
    private final int REFRESH = 0;
    private final int LOAD = 1;
    private final int SEND = 2;
    private final int DEFAULT = -1;

    private CommentAdapter mAdapter;
    protected SwipeMenuRecyclerView mRecyclerView;
    private TwinklingRefreshLayout mRefreshView;
    private TextView mSendView;
    private EditText mEtView;
    private View mVcomment;
    private RelativeLayout mComment;
    private boolean isHasMenuOpening = false;
    private int openMenuPosition = -1;

    private static final String FEED = "feed";
    private static final String POSITION = "position";

    private FeedModel feedModel;
    private int position;
    private int feedId;
    private int mSinceId = 0;
    private int mMaxId = 0;
    private int mCount = 20;

    private long replyToUid = -1;
    private long uid = -1;
    private String replyName;

    private String commentUpdateRequest;
    private String feedCommentListRequest;
    private String commentDelRequest;

    boolean updateStatus = false;

    private int countComment;

    private InputMethodManager imm;

    private KeyboardChangeListener mKeyboardChangeListener;

    private LoadView loadComment;
    private boolean isClick = false;

    public static void startActivity(Activity context, FeedModel feedModel, int position, int request) {
        Intent intent = new Intent(context, CommentActivity.class);
        intent.putExtra(FEED, feedModel);
        intent.putExtra(POSITION, position);
        context.startActivityForResult(intent, request);
    }

    @Override
    protected boolean isTranslucentStatus() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_dynamics_comment;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        com.imay.live.utils.ViewUtil.setForgroundRadius($(R.id.rl_comment));

        isClick = false;
        setTitle(getString(R.string.str_dynamics_comment_title));
        getTitleBar().setLeftImageOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (updateStatus || countComment != feedModel.getCountComment()) {
                    feedModel.setCountComment(countComment);
                    /**
                     * 修改评论数目
                     */
                    DymaicsUpdateHelper.modifyDynamics(feedModel);
                }
                finish();
            }
        });
        mContext = this;
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        feedModel = getIntent().getParcelableExtra(FEED);
        position = getIntent().getIntExtra(POSITION, -1);
        feedId = feedModel.getFeedId();
        uid = feedModel.getUid();

        initWidget();
        initDatas();
        initListener();
        if (mEtView != null) {
            mEtView.requestFocus();
        }
    }

    public void attachKeyboard(Activity activity) {
        //KeyboardUtil.attach(activity, mPanelRoot, null);
        //KPSwitchConflictUtil.attach(mPanelRoot, mVcomment, mEtView);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (command.equals(commentUpdateRequest)) {  // 操作评论
            updateStatus = true;
            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.result == 0) {
                replyToUid = -1;
                replyName = "";
                mEtView.setText("");
                countComment = result.data.getInteger("countComment");
                status = SEND;
                if (mAdapter.getData().isEmpty()) {
                    loadComments(mSinceId, mMaxId, mCount);
                } else {
                    loadComments(mAdapter.getData().get(0).getId(), mMaxId, mCount);
                }
            } else {
                ErrorResult.toastError(mContext, result.result);
            }
        } else if (command.equals(feedCommentListRequest)) {  // 加载评论
            loadComment.setVisibility(View.GONE);
            loadComment.stopLoading();
            Result<CommentTotalModel> result = JSON.parseObject(data, new TypeReference<Result<CommentTotalModel>>() {
            }.getType());
            countComment = result.data.getCountComment();
            List<CommentModel> comments = result.data.getComments();
            if (comments == null || comments.isEmpty()) {
                mRefreshView.finishRefreshing();
                mRefreshView.finishLoadmore();
                if (status == REFRESH || status == DEFAULT) {
                    loadComment.setVisibility(View.VISIBLE);
                    loadComment.loadError();
                }
            } else {
                if (status == REFRESH) { // 刷新
                    mAdapter.setNewData(comments);
                    mRefreshView.finishRefreshing();
                } else if (status == LOAD) { // 加载
                    mAdapter.addData(comments);
                    mRefreshView.finishLoadmore();
                } else if (status == SEND) { // 发送
                    mAdapter.addData(0, comments);
                    mRecyclerView.scrollToPosition(0);
                } else {
                    mAdapter.setNewData(comments);
                }
            }
        } else if (command.equals(commentDelRequest)) { // 删除评论
            updateStatus = true;
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.result == 0) {
                replyToUid = -1;
                replyName = "";
                mEtView.setText("");
                countComment = result.data.getInteger("countComment");
                if (countComment == 0) {
                    loadComment.setVisibility(View.VISIBLE);
                    loadComment.loadError();
                } else {
                    loadComment.setVisibility(View.GONE);
                }
                status = DEFAULT;
            } else {
                ErrorResult.toastError(mContext, result.result);
            }
        }
    }


    @Override
    public void onRequestError(String command, int code, String message) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        ErrorResult.toastError(this, code);
        if (status == REFRESH) { // 刷新
            mRefreshView.finishRefreshing();
            if (code == 10001) {
                loadComment.netError();
            } else {
                String error = ErrorResult.getString(mContext, 1);
                loadComment.loadError(error);
            }
        } else if (status == LOAD) { // 加载
            mRefreshView.finishLoadmore();
        }
    }

    private void initListener() {
        //attachKeyboard(this);
        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);

        mAdapter.setListener(this);

        mVcomment.setOnClickListener(this);

        mEtView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    showInputView();
                } else {
                    // 此处为失去焦点时的处理内容
                    hideInputView();
                }
            }
        });

        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {

            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CommentModel comment = mAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.civ_item_comment_img:
                        ProfileActivity.start(mContext, comment.getUser().getUid());
                        break;
                    case R.id.tv_comment_name:
                    case R.id.item_comment_menu1: // 回复
                        SwipeHorizontalMenuLayout layout = (SwipeHorizontalMenuLayout) view.getParent().getParent();
                        layout.smoothCloseMenu();
                        replyToUid = comment.getUser().getUid();
                        replyName = " @" + comment.getUser().getNick() + " ";
                        SpannableStringBuilder spannableStringBuilder = SpannableStringUtils.getBuilder(replyName).setFlag(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE).create();
                        mEtView.setText(spannableStringBuilder);
                        mEtView.setSelection(replyName.length());
                        mEtView.requestFocus();
                        mEtView.setFocusable(true);
                        if (imm != null) {
                            imm.showSoftInput(mEtView, 0);
                        }
                        showInputView();
                        break;
                    case R.id.sml_comment:
                        if (isClick) {
                            isClick = false;
                            return;
                        }
                        layout = (SwipeHorizontalMenuLayout) view;
                        if (layout.isMenuOpen()) {
                            layout.smoothCloseMenu();
                        } else if (isShowInputView()) {
                            if (imm != null) {
                                imm.hideSoftInputFromWindow(mEtView.getWindowToken(), 0);
                            }
                            hideInputView();
                        } else if (!isHasMenuOpening) {
                            replyToUid = comment.getUser().getUid();
                            replyName = " @" + comment.getUser().getNick() + " ";
                            spannableStringBuilder = SpannableStringUtils.getBuilder(replyName).setFlag(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE).create();
                            mEtView.setText(spannableStringBuilder);
                            mEtView.setSelection(replyName.length());
                            mEtView.requestFocus();
                            mEtView.setFocusable(true);
                            if (imm != null) {
                                imm.showSoftInput(mEtView, 0);
                            }
                            showInputView();
                        }
                        break;
                    case R.id.item_comment_menu2: // 删除
                        isHasMenuOpening = false;
                        layout = (SwipeHorizontalMenuLayout) view.getParent().getParent();
                        layout.smoothCloseMenu();
                        mAdapter.remove(position);
                        delComment(comment.getId());
                        break;
                }
            }
        });

        mRefreshView.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                status = REFRESH;
                loadComments(mSinceId, mMaxId, mCount);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                status = LOAD;
                List<CommentModel> comment = mAdapter.getData();
                if (comment.isEmpty()) {
                    mRefreshView.finishLoadmore();
                    return;
                }
                CommentModel item = comment.get(comment.size() - 1);
                loadComments(mSinceId, item.getId(), mCount);
            }
        });

        // 模块删除@人
        mEtView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                    //当为删除键并且是按下动作时执行
                    int selectionStart = mEtView.getSelectionStart();
                    int lastPos = 0;
                    if (!TextUtils.isEmpty(replyName)) {
                        if ((lastPos = mEtView.getText().toString().indexOf(replyName, lastPos)) != -1) {
                            if (selectionStart != 0 && selectionStart >= lastPos && selectionStart <= (lastPos + replyName.length())) {
                                String sss = mEtView.getText().toString();
                                mEtView.setText(sss.substring(0, lastPos) + sss.substring(lastPos + replyName.length()));
                                mEtView.setSelection(lastPos);
                                return true;
                            } else {
                                lastPos += replyName.length();
                            }
                        }
                    }
                }
                return false;
            }
        });

        mSendView.setOnClickListener(this);
    }


    /**
     * 删除评论
     *
     * @param commentId
     */
    private void delComment(int commentId) {
        if (!NetworkHelper.getInstance().hasConnection()) {
            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
            ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
            return;
        }
        commentDelRequest = ProtoRequestHelper.task(ProtoHttpFactory.commentDel(feedId, commentId)).setTag(this.hashCode()).request(this);
    }

    /**
     * 发送信息
     *
     * @param msg
     */
    private void send(String msg) {
        if (!NetworkHelper.getInstance().hasConnection()) {
            ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
            return;
        }
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_comment_loading));
        commentUpdateRequest = ProtoRequestHelper.task(ProtoHttpFactory.commentCreate(feedId, msg, replyToUid)).setTag(this.hashCode()).request(this);
    }

    private void initWidget() {
        loadComment = $(R.id.lv_comment);

        mComment = $(R.id.rl_comment);
        mSendView = $(R.id.tv_comment_sent);
        mEtView = $(R.id.et_comment_str);
        mVcomment = $(R.id.v_comment);
        mVcomment.setVisibility(View.VISIBLE);
        mVcomment.setBackgroundColor(Color.TRANSPARENT);

        mAdapter = new CommentAdapter(uid);

        mRefreshView = $(R.id.comment_trl_refresh);

        mRefreshView = $(R.id.comment_trl_refresh);
        mRefreshView.setHeaderView(new RefreshView(mContext));
        mRefreshView.setEnableRefresh(true);
        mRefreshView.setBottomView(new LoadingView(mContext));
        mRefreshView.setEnableLoadmore(true);
        mRefreshView.setEnableOverScroll(false);

        mRecyclerView = $(R.id.lrcv_content);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        mRecyclerView.setHasFixedSize(true);

        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .colorResId(R.color.line_f4)
                .sizeResId(R.dimen.divider_size_1x)
                .marginResId(R.dimen.size_80dp, R.dimen.size_0dp)
                .build());

        mRecyclerView.setAdapter(mAdapter);

        EditTextManager.getInstance().changeBgColor(mSendView, R.drawable.shape_corner100_bc, R.drawable.shape_corner100_30, mEtView);
    }

    private void initDatas() {
        loadComment.setVisibility(View.VISIBLE);
        loadComment.startLoading();
        if (feedId != -1) {
            status = DEFAULT;
            loadComments(mSinceId, mMaxId, mCount);
        }
    }

    /**
     * 获取数据
     *
     * @param sinceId
     * @param maxId
     * @param count
     */
    private void loadComments(final int sinceId, final int maxId, int count) {
        feedCommentListRequest = task(ProtoHttpFactory.feedCommentList(feedId, sinceId, maxId, count)).setTag(this.hashCode()).request(this);
    }

    @Override
    public void jinClick(String label) {
        isClick = true;
        LabelFeedsActivity.startActivity(this, label);
    }

    @Override
    public void atClick(String nick, long uid) {
        isClick = true;
        ProfileActivity.start(mContext, uid);
    }

    @Override
    public void beginMenuOpened(int position) {
        isHasMenuOpening = true;
        openMenuPosition = position;
    }

    @Override
    public void endMenuClosed(int position) {
        isHasMenuOpening = false;
        openMenuPosition = -1;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_comment_sent:
                Editable ed = mEtView.getText();
                if (!TextUtils.isEmpty(ed)) {
                    if (!SensitiveWordFilterManager.getInstance().hasSensitiveWord(mEtView)) {
                        ThreadManager.post(new Runnable() {
                            @Override
                            public void run() {
                                if (imm != null) {
                                    imm.hideSoftInputFromWindow(mEtView.getWindowToken(), 0);
                                }
                            }
                        });
                        String msg = ed.toString();
                        send(msg);
                    } else {
                        ToastUtil.show(mContext, R.string.sensitive_comment);
                    }
                }
                break;
            case R.id.v_comment:
                if (imm != null) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                hideInputView();
                break;
            case R.id.et_comment_str:
                showInputView();
                break;
        }
    }

    public boolean isShowInputView() {
        return mVcomment.getVisibility() != View.GONE;
    }

    //隐藏输入框，显示其他控件
    @CallSuper
    public void hideInputView() {
        if (isShowInputView()) {
            //KPSwitchConflictUtil.hidePanelAndKeyboard(mPanelRoot);
            mVcomment.setVisibility(View.GONE);
        }
    }

    //显示输入框
    @CallSuper
    protected void showInputView() {
        //KPSwitchConflictUtil.showKeyboard(mPanelRoot, mEtView);
        //mPanelRoot.setVisibility(View.INVISIBLE);
        mVcomment.setVisibility(View.VISIBLE);
    }

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        if (isShow) {
            showInputView();
            if (openMenuPosition != -1) {
                RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
                View content = layoutManager.findViewByPosition(openMenuPosition);
                if (content != null) {
                    SwipeHorizontalMenuLayout menuLayout = $(R.id.sml_comment, content);
                    try {
                        if (menuLayout != null && menuLayout.isMenuOpen()) {
                            menuLayout.smoothCloseMenu();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            hideInputView();
        }
    }

    @Override
    public void finish() {
        if (imm != null) {
            imm.hideSoftInputFromWindow(mEtView.getWindowToken(), 0);
        }
        ThreadManager.postDelayed(new Runnable() {
            @Override
            public void run() {
                CommentActivity.super.finish();
            }
        }, 200);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mKeyboardChangeListener != null) {
            mKeyboardChangeListener.destroy();
        }
        if (imm != null) {
            imm = null;
        }
    }
}
